package com.example.chamberlainserver.Service.impl;

import com.example.chamberlainserver.Entry.Role;
import com.example.chamberlainserver.Entry.UserRole;
import com.example.chamberlainserver.Service.UserRoleService;
import com.example.chamberlainserver.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户角色关联服务实现类
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public List<UserRole> getUserRolesByUserId(Integer userId) {
        return userRoleMapper.getUserRolesByUserId(userId);
    }

    @Override
    public List<UserRole> getUserRolesByRoleId(Integer roleId) {
        return userRoleMapper.getUserRolesByRoleId(roleId);
    }

    @Override
    public List<Role> getRolesByUserId(Integer userId) {
        return userRoleMapper.getRolesByUserId(userId);
    }

    @Override
    public boolean addUserRole(UserRole userRole) {
        return userRoleMapper.insertUserRole(userRole) > 0;
    }

    @Override
    public boolean batchAddUserRole(List<UserRole> userRoles) {
        if (userRoles == null || userRoles.isEmpty()) {
            return false;
        }
        return userRoleMapper.batchInsertUserRole(userRoles) > 0;
    }

    @Override
    public boolean deleteUserRole(Integer userId, Integer roleId) {
        return userRoleMapper.deleteUserRole(userId, roleId) > 0;
    }

    @Override
    public boolean deleteUserRolesByUserId(Integer userId) {
        return userRoleMapper.deleteUserRolesByUserId(userId) > 0;
    }

    @Override
    public boolean deleteUserRolesByRoleId(Integer roleId) {
        return userRoleMapper.deleteUserRolesByRoleId(roleId) > 0;
    }

    @Override
    public boolean hasRole(Integer userId, Integer roleId) {
        return userRoleMapper.hasRole(userId, roleId);
    }

    @Override
    public boolean hasRoleByCode(Integer userId, String roleCode) {
        return userRoleMapper.hasRoleByCode(userId, roleCode);
    }

    @Override
    @Transactional
    public boolean assignRolesToUser(Integer userId, List<Integer> roleIds) {
        // 先删除用户现有的所有角色
        userRoleMapper.deleteUserRolesByUserId(userId);
        
        // 如果角色ID列表为空，则只是清空用户角色
        if (roleIds == null || roleIds.isEmpty()) {
            return true;
        }
        
        // 批量添加新的用户角色关联
        List<UserRole> userRoles = new ArrayList<>();
        for (Integer roleId : roleIds) {
            userRoles.add(new UserRole(userId, roleId));
        }
        
        return userRoleMapper.batchInsertUserRole(userRoles) > 0;
    }
}